/*
 * 搜索组件
 */
import PropTypes from 'prop-types';
import { Form, Input, Select, Button } from 'antd';
import { USER_STATUS_MAP } from '../constants';

const FormItem = Form.Item;
const { Option } = Select;

function SearchForm({ form, onSearch, onCreate }) {
  function handleFormReset() {
    form.resetFields();
  }

  function handleCreate() {
    onCreate();
  }

  function handleFormSearch(e) {
    e.preventDefault();

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      let filters = {};
      Object.keys(fieldsValue).forEach(key => {
        const val = fieldsValue[key];
        if (val) {
          // 转换下key，这里没用name，因为和Modal里面的name冲突了
          if (key === 's_name') {
            key = 'name';
          }

          filters[key] = val;
        }
      });

      onSearch(filters, true);
    });
  }

  const { getFieldDecorator } = form;

  return (
    <Form onSubmit={handleFormSearch.bind(this)} layout="inline">
      <FormItem label="姓名">
        {getFieldDecorator('s_name')(<Input style={{ width: 200 }} placeholder="请输入用户姓名" />)}
      </FormItem>
      <FormItem label="状态">
        {getFieldDecorator('status')(
          <Select placeholder="请选择" style={{ width: 200 }}>
            {USER_STATUS_MAP.map(item => (
              <Option key={item.status} value={item.status}>
                {item.desc}
              </Option>
            ))}
          </Select>
        )}
      </FormItem>
      <FormItem>
        <div style={{ overflow: 'hidden' }}>
          <span style={{ marginBottom: 24 }}>
            <Button icon="search" type="primary" htmlType="submit">
              查询
            </Button>
            <Button icon="reset" style={{ marginLeft: 8 }} onClick={handleFormReset}>
              重置
            </Button>
            <Button icon="plus" style={{ marginLeft: 8 }} type="primary" onClick={handleCreate}>
              添加
            </Button>
          </span>
        </div>
      </FormItem>
    </Form>
  );
}

if (process.env.UMI_ENV !== 'prod') {
  SearchForm.propTypes = {
    onSearch: PropTypes.func.isRequired,
    onCreate: PropTypes.func.isRequired,
    form: PropTypes.object.isRequired,
  };
}

SearchForm.defaultProps = {
  onSearch: () => {},
  onCreate: () => {},
  form: {},
};
export default Form.create()(SearchForm);
